#!/usr/bin/env python
# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from dateutil.relativedelta import relativedelta

class SbProductTimeoutRef(models.Model):
    _name = 'sb.product.timeout.ref'
    _description = 'Product Timeout Reference'

    product_categ_id = fields.Many2one(
        'product.category',
        string="Product Category",
        required=True,
        index=True
    )
    #  location_id = fields.Many2one('stock.location', 'Check Stock Location', default=lambda self:self.env['stock.location'].search([('id','=',28)]), readonly=True)
    location_id = fields.Many2one('stock.location', 'Check Stock Location', default=lambda self:self.env['stock.location'].search([('id','=',28)]), 
                                    domain = lambda self: [('location_id', '=', self.env.ref('stock.stock_location_stock').id)],
                                  readonly=True)


    def _get_default_location_id(self):
        return self.env.ref('stock.stock_location_stock')

    s_expiration_days = fields.Integer(string="Expiration Days")
    s_removel_days = fields.Integer(string="Removel Days")
    s_use_days = fields.Integer(string="Use Days")
    s_alert_days = fields.Integer(string="Alert Days")
    s_force_expiration = fields.Boolean(string="Force Expiration")

    _sql_constraints = [
        ('product_categ_unique', 'UNIQUE(product_categ_id)', '每个产品分类只能有一个有效期配置!'),
    ]

    def batch_update_use_expiration_date(self):
        for row in self.filtered(lambda x:x.s_force_expiration):
            products = self.env['product.product'].search([('categ_id','=',row.product_categ_id.id)])
            products.update({'use_expiration_date':True})

    def to_compute_dates(self):
        """ 根据生产日期和有效期配置计算各个日期 """
        for row in self:
            products = self.env['product.product'].search([('categ_id','=',row.product_categ_id.id)])
            if not row.s_force_expiration:
                products = products.filtered(lambda x:x.use_expiration_date)
            for p_row in products:
                expiration_days = p_row.expiration_time if p_row.expiration_time else row.s_expiration_days
                if expiration_days <= 0:
                    continue
                stock_rows = p_row.stock_quant_ids.filtered(lambda x:x.location_id == row.location_id).lot_id
                for stock_row in stock_rows.filtered(lambda x:x.production_date):
                    stock_row.expiration_date  = stock_row.production_date + relativedelta(days=expiration_days)

#class StockLot(models.Model):
#    _inherit = 'stock.lot'
#
#    def _process_expired_lots(self):
#        """
#        自定义方法：扫描所有到期批次，并触发移库操作
#        """
#        # 获取所有已到期的批次
#        expired_lots = self.search([
#            ('expiration_date', '<=', fields.Date.today()),
#            ('product_qty', '>', 0),
#        ])
#
#        # 遍历每个到期批次
#        for lot in expired_lots:
#            # 查找目标库位（例如：质检库位，需预先创建）
#            dest_location = self.env.ref('sb_product_expiry_ext.stock_location_quality_control', raise_if_not_found=False)
#            if not dest_location:
#                continue  # 如果目标库位不存在则跳过
#
#            # 创建调拨单
#            move = self.env['stock.move'].create({
#                'name': f'到期移库 - {lot.name}',
#                'product_id': lot.product_id.id,
#                'product_uom': lot.product_id.uom_id.id,
#                'location_id': lot.location_id.id,       # 来源库位
#                'location_dest_id': dest_location.id,    # 目标库位
#                'product_uom_qty': lot.product_qty,
#                'lot_ids': [(4, lot.id)],
#            })
#            # 确认并完成调拨单
#            move._action_confirm()
#            move._action_assign()
#            move._action_done()
